<template>
	<view class="doctor-list-page">

		<!-- 搜索栏 -->
		<view class="search-box">
			<uni-icons class="search-icon" type="search" size="40rpx" color="#00CC71"></uni-icons>
			<input class="search-input" placeholder="输入医生/疾病搜索" @input="handleSearchInput" />
		</view>

		<!-- 专家推荐横向滚动 -->
		<view style="display: flex;align-items: center;height: 50rpx;margin-bottom: 35rpx;">
			<view class="green-bar"></view>
			<view class="section-title">专家推荐</view>
		</view>
		<scroll-view class="expert-scroll" scroll-x>
			<view class="expert-card"v-for="(item, index) in doctors" :key="index" @click="gochat">
				<image class="expert-avatar" :src="item.avatar" ></image>
				<text class="expert-name">{{item.name}}</text>
				<text class="expert-title">主任医生</text>
			</view>
		</scroll-view>

		<!-- 筛选栏与医生列表 -->
		<view class="list-container">
			<!-- 筛选栏 -->
			<view class="filter-bar">
				<!-- 医院筛选 -->
				<view class="filter-item" @click="toggleDropdown('hospital')">
					{{ selectedHospital }}<span class="triangle">▼</span>
					<view v-if="showDropdown === 'hospital'" class="dropdown-menu"></view>
				</view>

				<!-- 科室筛选 -->
				<view class="filter-item" @click="toggleDropdown('department')">
					{{ selectedDepartmentTitle }}<span class="triangle">▼</span>
					<view v-if="showDropdown === 'department'" class="dropdown-menu">
						<view  class="dropdown-item" v-for="(item, index) in departmentOptions.slice(1)" :key="index"
							@click.stop="selectOption('department', item.title)" style="height: 20px;">
							{{ item.title }}
						</view>
					</view>
				</view>

				<!-- 职称筛选 -->
				<view class="filter-item" @click="toggleDropdown('title')">
					{{ selectedTitle }}<span class="triangle">▼</span>
					<view v-if="showDropdown === 'title'" class="dropdown-menu">
					</view>
				</view>
			</view>

			<!-- 分割线 -->
			<view class="divider"></view>

			<!-- 医生列表 -->
			<scroll-view class="doctor-scroll" scroll-y>
				<view class="doctor-card" v-for="(item, index) in doctors" :key="index">
					<image class="doctor-avatar" :src="item.avatar || '/static/doctor.png'" ></image>
					<view class="doctor-info">
						<text class="doctor-name">{{ item.name }}</text>
						<text class="doctor-hospital">{{ getHospitalName(item.hid) }}</text>
						<text class="doctor-specialty">
							<text class="specialty-label">擅长：</text>
							<text class="specialty-content">{{ item.good_at }}</text>
						</text>
						<text class="doctor-title">{{ item.grade }}</text>
					</view>
					<image class="consult-icon" src="/static/zix.png" mode="aspectFit" @click="gochat"></image>
				</view>

				<view v-if="doctors.length === 0 && !isLoading" class="empty-tips">
					<text>暂无符合条件的医生</text>
				</view>

				<!-- 加载中提示 -->
				<view v-if="isLoading" class="loading">
					<text>加载中...</text>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue'
	// import navVue from '../../components/nav.vue';
	import {
		debounce
	} from 'lodash-es'

	// 响应式数据
	const title = ref('在线问诊')
	const selectedHospital = ref('全部医院')
	const selectedDepartment = ref(null)
	const selectedTitle = ref('全部职称')
	const showDropdown = ref(null)
	const isLoading = ref(false)
	const doctors = ref([])
	const searchKey = ref('')

	// 筛选选项
	const hospitalOptions = ref([])
	const departmentOptions = ref([])

	// 计算属性
	const selectedDepartmentTitle = computed(() => {
		return selectedDepartment.value?.title || '全部科室'
	})

	// 获取医院名称
	const getHospitalName = (hid) => {
		const hospital = hospitalOptions.value.find(h => h.hid === hid)
		return hospital ? hospital.title : '未知医院'
	}

	// 切换下拉菜单显示/隐藏
	const toggleDropdown = (type) => {
		showDropdown.value = showDropdown.value === type ? null : type
	}



	// 加载科室列表
	const loadDepartments = async () => {

		if (selectedHospital.value === '全部医院') {
			departmentOptions.value = []
			selectedDepartment.value = null
			return
		}

		const selectedHospitalItem = hospitalOptions.value.find(
			item => item.title === selectedHospital.value
		)
		if (!selectedHospitalItem) return
		console.log(selectedHospitalItem.hid);
		try {
			const [err, res] = await new Promise((resolve) => {
				uni.request({
					url: 'http://localhost:3010/hospital/subject',
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'Authorization': `Bearer ${uni.getStorageSync('token')}`,
					},
					data: {
						hid: selectedHospitalItem.hid // 传递医院ID获取对应科室
					},
					success: (res) => resolve([null, res]),
					fail: (err) => resolve([err, null])
				})
			})
			console.log('科室', res.data);
			if (err) throw err

			if (res.data && res.data.code === 200) {
				// 处理科室数据
				const departments = Array.isArray(res.data.data.result) ? res.data.data.result : []

				// 构建科室选项（添加"全部科室"作为第一个选项）
				departmentOptions.value = [{
					did: null,
					title: '全部科室'
				}, ...departments]
				selectedDepartment.value = null
			} else {
				console.warn('加载科室失败:', res.data?.msg)
				departmentOptions.value = [{
					did: null,
					title: '全部科室'
				}]
			}
		} catch (err) {
			console.error('加载科室出错:', err)
			departmentOptions.value = [{
				did: null,
				title: '全部科室'
			}]
		}
	}

	// 搜索输入处理
	const handleSearchInput = debounce((e) => {
		searchKey.value = e.detail.value.trim()
		if (searchKey.value.length > 0) {
			searchDoctors() // 关键词搜索
		} else {
			loadDoctors() // 无关键词时加载全部（带筛选条件）
		}
	}, 500)

	// 加载医生列表（带筛选条件）
	const loadDoctors = async () => {
		isLoading.value = true
		try {
			// 构建请求参数 - 只包含后端支持的参数
			const params = {
				page: 1,
				pagenum: 20
			}

			console.log('加载医生列表参数:', params) // 添加日志

			const [err, res] = await new Promise((resolve) => {
				uni.request({
					url: 'http://localhost:3010/doctor/list',
					method: 'GET',
					data: params,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'Authorization': `Bearer ${uni.getStorageSync('token')}`,
					},
					success: (res) => resolve([null, res]),
					fail: (err) => resolve([err, null])
				})
			})

			if (err) throw err

			console.log('医生列表响应:', res.data) // 添加日志

			if (res.data && res.data.code === 200) {
				doctors.value = Array.isArray(res.data.data?.result) ? res.data.data.result : []

				// 前端过滤职称（如果后端不支持）
				if (selectedTitle.value !== '全部职称') {
					doctors.value = doctors.value.filter(doctor => doctor.grade === selectedTitle.value)
				}
			} else {
				console.warn('加载医生列表失败:', res.data?.msg)
				doctors.value = []
			}
		} catch (err) {
			console.error('加载医生列表出错:', err)
			doctors.value = []

			// 显示用户友好提示
			uni.showToast({
				title: '加载医生列表失败，请稍后重试',
				icon: 'none'
			})
		} finally {
			isLoading.value = false
		}
	}

	const searchDoctors = async () => {
		isLoading.value = true;
		try {
			// 只传关键词参数，忽略筛选条件
			const params = {
				key: searchKey.value || '', // 允许空搜索（返回全部医生）
			};

			const [err, res] = await new Promise((resolve) => {
				uni.request({
					url: `http://localhost:3010/doctor/search?key=${encodeURIComponent(params.key)}`,
					method: 'GET',
					header: {
						'Authorization': `Bearer ${uni.getStorageSync('token')}`,
					},
					success: (res) => resolve([null, res]),
					fail: (err) => resolve([err, null])
				});
			});

			if (err) throw err;

			if (res.data && res.data.code === 200) {
				doctors.value = Array.isArray(res.data.data) ? res.data.data : [];
			} else {
				// 增强错误信息提取
				const errorMsg =
					res.data?.msg || // 优先使用 msg 字段
					res.data?.error?.message || // 尝试 error.message 字段
					JSON.stringify(res.data) || // 使用完整响应数据
					'搜索失败，请重试'; // 默认提示

				console.warn('搜索失败:', errorMsg, res.data); // 打印完整响应
				doctors.value = [];
				uni.showToast({
					title: errorMsg,
					icon: 'none'
				});
			}
		} catch (err) {
			console.error('搜索出错:', err);
			doctors.value = [];
			uni.showToast({
				title: '搜索失败，请稍后重试',
				icon: 'none'
			});
		} finally {
			isLoading.value = false;
		}
	};

	// 筛选条件选择（保留UI交互，但不触发筛选逻辑）
	const selectOption = (type, value) => {
		// 更新选中值
		if (type === 'hospital') {
			selectedHospital.value = value;
		} else if (type === 'department') {
			selectedDepartment.value = value;
		} else if (type === 'title') {
			selectedTitle.value = value;
		}

		showDropdown.value = null; // 关闭下拉菜单

		// 仅在有搜索关键词时触发搜索
		if (searchKey.value.length > 0) {
			searchDoctors();
		}
		loadDepartments()
	};

	// 初始化加载
	onMounted(() => {
		// 并行加载医院列表和专家推荐
		Promise.all([
			// 加载医院列表
			new Promise((resolve) => {
				uni.request({
					url: 'http://localhost:3010/hospital/limit',
					method: 'POST',
					data: {
						page: 1,
						pagenum: 20
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'Authorization': `Bearer ${uni.getStorageSync('token')}`,
					},
					success: (res) => {
						if (res.data && res.data.code === 200) {
							hospitalOptions.value = Array.isArray(res.data.data?.result) ?
								res.data.data.result : []
						} else {
							console.error('加载医院列表失败:', res.data?.msg)
						}
						resolve()
					},
					fail: (err) => {
						console.error('加载医院列表出错:', err)
						resolve()
					}
				})
			}),

		]).then(() => {
			// 医院列表加载完成后，加载医生列表
			loadDoctors()
		})
	})
	
	const gochat=()=>{
		uni.navigateTo({
			url:'/pages/chat/chat'
		})
	}
</script>

<style>
	/* 全局样式 */
	page {
		background-color: #e1e1e1;
		height: 100%;
	}

	/* 页面容器 */
	.doctor-list-page {
		padding: 20rpx;
		height: 100vh;
		box-sizing: border-box;
	}

	/* 搜索框 */
	.search-box {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 15rpx;
		width: 610rpx;
		padding: 20rpx 30rpx;
		box-shadow: 10rpx 6rpx 19rpx rgba(71, 220, 64, 0.3);
		height: 50rpx;
		margin: 10rpx auto 40rpx;
	}

	.search-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #999;
		height: 100%;
	}

	/* 专家推荐 */
	.green-bar {
		width: 8rpx;
		height: 40rpx;
		background-color: #00ff06;
		border-radius: 4rpx;
		margin-right: 20rpx;
		margin-left: 20rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	/* 专家推荐横向滚动 */
	.expert-scroll {
		white-space: nowrap;
		margin-bottom: 20px;
	}

	.expert-card {
		display: inline-block;
		width: 100px;
		text-align: center;
		margin-right: 15px;
		margin-left: 10rpx;
		background: white;
		border-radius: 8px;
		padding: 10px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	}

	.expert-avatar {
		width: 50px;
		height: 50px;
		border-radius: 50%;
		background-color: #eee;
	}

	.expert-name {
		display: block;
		font-size: 12px;
		color: #333;
		margin-bottom: 5rpx;
	}

	.expert-title {
		display: block;
		font-size: 12px;
		color: #666;
	}

	/* 列表容器 */
	.list-container {
		background: white;
		border-radius: 16rpx;
		overflow: hidden;
		margin-top: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		display: flex;
		justify-content: center;
		width: 670rpx;
		flex-direction: column;
		margin-left: 20rpx;
	}

	/* 筛选栏 */
	.filter-bar {
		display: flex;
		justify-content: space-between;
		padding: 30rpx;
		background: white;
	}

	/* 下拉菜单 */
	.dropdown-menu {
		position: absolute;
		top: 100%;
		left: 0;
		background: white;
		border-radius: 8rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
		z-index: 100;
		min-width: 200rpx;
		max-height: 400rpx;
		overflow-y: auto;
	}

	.dropdown-item {
		/* 统一内边距，和第一条保持一致 */
		padding: 20rpx 30rpx;
		/* 统一字体大小、颜色 */
		font-size: 12px;
		color: #333;
		/* 统一边框样式 */
		border-bottom: 1rpx solid #f0f0f0;
		/* 确保行高一致，文字垂直居中 */
		line-height: 1.5;
		/* 去除默认的 margin，避免间距不一致 */
		margin: 0;
	}

	.dropdown-item:last-child {
		border-bottom: none;
	}

	.dropdown-item:active {
		background-color: #f5f5f5;
	}

	.filter-item {
		position: relative;
		height: 20px;
		font-size: 12px;
		color: #333;
		display: flex;
		align-items: center;
	}

	.triangle {
		font-size: 15rpx;
		margin-left: 10rpx;
		color: #999;
	}

	/* 分割线 */
	.divider {
		height: 3rpx;
		background-color: #f0f0f0;
		margin: 0 30rpx;
	}

	/* 医生列表 */
	.doctor-scroll {
		height: calc(100vh - 620rpx);
	}

	.doctor-card {
		display: flex;
		margin-left: 20rpx;
		padding: 30rpx;
		position: relative;
		height: 200rpx;
	}

	.doctor-avatar {
		width: 90rpx;
		height: 90rpx;
		border-radius: 50%;
		margin-right: 30rpx;
	}

	.doctor-info {
		flex: 1;
	}

	.doctor-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		display: block;
	}

	.doctor-hospital {
		font-size: 26rpx;
		color: #666;
		display: block;
	}

	.doctor-specialty {
		font-size: 26rpx;
		display: block;
		line-height: 1.6;
	}

	.doctor-title {
		font-size: 24rpx;
		color: #666;
		display: block;
	}

	.specialty-label {
		color: #999;
	}

	.specialty-content {
		color: chocolate;
	}

	/* 咨询图标 */
	.consult-icon {
		width: 150rpx;
		height: 150rpx;
		position: absolute;
		right: 40rpx;
		top: 120rpx;
	}

	/* 空状态提示 */
	.empty-tips {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	/* 筛选激活状态 */
	.filter-item.active {
		color: #4a90e2;
	}

	/* 加载动画 */
	.loading {
		display: flex;
		justify-content: center;
		padding: 20rpx;
	}
</style>